# -*- coding: utf-8 -*-

import logging
import random
from scrapy import signals
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware
from scrapy.downloadermiddlewares.retry import RetryMiddleware

import base64

# 代理服务器
from scrapy.http import HtmlResponse
from twisted.web.error import SchemeNotSupported

proxyServer = "http://http-dyn.abuyun.com:9020"

# 代理隧道验证信息
proxyUser = "HFYW457OV8G521RD"
proxyPass = "6983B6E471C57DAA"
proxyAuth = "Basic " + base64.urlsafe_b64encode(bytes((proxyUser + ":" + proxyPass), "ascii")).decode("utf8")

class LactationerMasterSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        print('get process_spider_exception: ', response)
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            # Set the location of the proxy
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

class LactationerMiddleware(UserAgentMiddleware):
    def __init__(self, user_agent):
        self.user_agent = user_agent

    # 从setting.py中引入设置文件
    @classmethod
    def from_crawler(cls, crawler):
        return cls( user_agent=crawler.settings.get('MY_USER_AGENT'))

    # 设置User-Agent
    def process_request(self, request, spider):
        agent = random.choice(self.user_agent)
        request.headers['User-Agent'] = agent
        print(u'当前User-Agent:',request.headers['User-Agent'])


class ProxyMiddleware(object):
    def process_request(self, request, spider):
        # Set the location of the proxy
        request.meta['proxy'] = proxyServer
        request.headers["Proxy-Authorization"] = proxyAuth
        print(u'当前代理ip:', request.meta['proxy'])
        pass


class Process_Proxies(RetryMiddleware):
    logger = logging.getLogger(__name__)

    def process_response(self, request, response, spider):
        # if request.meta.get('dont_retry',False):
        #     return response
        # if response.status in self.retry_http_codes:
        if response.status != 200:
            print('状态码异常:', response.status)
            request.meta['proxy'] = proxyServer
            request.headers["Proxy-Authorization"] = proxyAuth
            return self._retry(request, response, spider) or response
        return response

    def process_exception(self, request, exception, spider):
        if isinstance(exception, self.EXCEPTIONS_TO_RETRY) and not request.meta.get('dont_retry', False):
            self.logger.warning('连接异常,进行重试......')
            request.meta['proxy'] = proxyServer
            request.headers["Proxy-Authorization"] = proxyAuth
        return self._retry(request, exception, spider)



from twisted.internet import defer
from twisted.internet.error import TimeoutError, DNSLookupError, \
    ConnectionRefusedError, ConnectionDone, ConnectError, \
    ConnectionLost, TCPTimedOutError
from twisted.web.client import ResponseFailed
from scrapy.core.downloader.handlers.http11 import TunnelError


class ProcessAllExceptionMiddleware(RetryMiddleware):
    ALL_EXCEPTIONS = (defer.TimeoutError, TimeoutError, DNSLookupError,
                      ConnectionRefusedError, ConnectionDone, ConnectError,
                      ConnectionLost, TCPTimedOutError, ResponseFailed,
                      IOError, TunnelError, SchemeNotSupported)

    def process_response(self, request, response, spider):
        # 捕获状态码为40x/50x的response
        if str(response.status).startswith('4') or str(response.status).startswith('5'):
            print('Got status: %s' % (response.status))
            request.meta['proxy'] = proxyServer
            request.headers["Proxy-Authorization"] = proxyAuth
            return response
        # 其他状态码不处理
        return response

    def process_exception(self, request, exception, spider):
        # 捕获几乎所有的异常
        print('Got exception， request: %s' % (request))
        if isinstance(exception, self.ALL_EXCEPTIONS):
            # 在日志中打印异常类型
            print('Got exception: %s' % (exception))
            # 随意封装一个response，返回给spider
        # 打印出未捕获到的异常
        print('not contained exception: %s' % exception)

        request.meta['proxy'] = proxyServer
        request.headers["Proxy-Authorization"] = proxyAuth
        response = HtmlResponse(url='exception')
        return response